package com.wangdong.yating.okhttp3;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.wangdong.yating.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 我们一直都说,用户体验很重要,当我们下载的文件比较大,
 * 而网速又比较慢的时候,如果我们只是在后台下载或上传,没有给用户显示一个进度,
 * 那将是非常差的用户体验,下面我们就将简单做一下进度的显示,其实非常简单的
 */
public class DownloadUploadProgressActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_upload_progress);
    }

    public void downloadImg(View view) {
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .get()
                .url("https://www.baidu.com/img/bd_logo1.png")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("moer", "onFailure: ");
                ;
            }

            @Override
            public void onResponse(Call call, Response response)
                    throws IOException {
                /**     下载 时候的进度
                 * 1.首先 要拿到下载文件的总大小
                 * 2.在while 循环中每次递增我们读取的buf的长度
                 *
                 * */


                InputStream is = response.body().byteStream();
                long sum = 0L;
                //文件总大小
                final long total = response.body().contentLength();
                int len = 0;
                File file = new File(Environment.getExternalStorageDirectory(), "n.png");
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buf = new byte[128];

                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                    //每次递增
                    sum += len;

                    final long finalSum = sum;
                    Log.d("pyh1", "onResponse: " + finalSum + "/" + total);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //将进度设置到TextView中
                            //                            contentTv.setText(finalSum + "/" + total);
                        }
                    });
                }
                fos.flush();
                fos.close();
                is.close();


            }
        });
    }

    public void UploadImgProgress(View view) {

        /** 对月上传的进度的处理会比较麻烦，应为具体的上传过程是在RequestBopdy中由
         *  okhttp帮我处理上传，而且okhttp并没有给我们上传进度的接口，这里我们的做法是自定义类继承RequestBody，然后
         *  我重写了其中的方法，将其中的上传进度通过接口回调暴露出来供我们使用
         *  */
        OkHttpClient client = new OkHttpClient();
        File file = new File(Environment.getExternalStorageDirectory(), "1.png");
        if (!file.exists()){
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
        }else{
            RequestBody requestBody2 = RequestBody.create(MediaType.parse("application/octet-stream"), file);


        //使用我们自己封装的类
        CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody2, new CountingRequestBody.Listener() {
            @Override
            public void onRequestProgress(long byteWritted, long contentLength) {
                //打印进度
                Log.d("pyh", "进度 ：" + byteWritted + "/" + contentLength);
            }
        });
        /*上面其实就是在原有的RequestBody上包装了一层,最后在我们的使用中在post()方法中传入我们的CountingRequestBody对象即可。*/
        final Request request =new Request.Builder()
                .url("http://www.jianshu.cmy")
                .post( countingRequestBody )
                .build();
        Call call =  client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
        }
    }

}
